package com.second.app.thread.线程基础.day07.线程通信.唤醒通知;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author GYZ
 * @Date 2023/11/29
 * <pre>
 *
 * </pre>
 */
public class OneProducerToManyConsumerDemo {
    public static void main(String[] args) {
        //一个生产者 多个消费者

        MyStack01 myStack = new MyStack01();
        P1 p = new P1(myStack);
        C1 c1 = new C1(myStack);
        C1 c2 = new C1(myStack);
        C1 c3 = new C1(myStack);
        C1 c4 = new C1(myStack);
        C1 c5 = new C1(myStack);

        p_thread01 p_thread = new p_thread01(p);
        p_thread.start();

        C_thread01 c_thread1 = new C_thread01(c1);
        C_thread01 c_thread2 = new C_thread01(c2);
        C_thread01 c_thread3 = new C_thread01(c3);
        C_thread01 c_thread4 = new C_thread01(c4);
        C_thread01 c_thread5 = new C_thread01(c5);

        c_thread1.start();
        c_thread2.start();
        c_thread3.start();
        c_thread4.start();
        c_thread5.start();
    }
}
class MyStack01 {
    private final List<String> myList = new ArrayList<>();

    synchronized public void push() {
        try {
            //因为条件发生改变时，没有得到及时得响应，所以多个呈wait状态得线程被唤醒，继而执行
            //list.remove(0)代码出现异常，所以将if改成while语句即可
            while (myList.size() == 1) {
                this.wait();
            }
            myList.add("anyThing=" + Math.random());
            this.notifyAll();
            System.out.println("push=" + myList.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public String pop() {
        String returnValue = "";
        try {
            while (myList.size() == 0) {
                System.out.println("pop 操作中的：" + Thread.currentThread().getName() + " 线程呈wait状态");
                this.wait();
            }
            returnValue = myList.get(0);
            myList.remove(0);
            this.notifyAll();
            System.out.println("pop=" + myList.size());

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return returnValue;
    }
}


//案例1 一消费加一生产
class p_thread01 extends Thread {

    public P1 p1;

    public p_thread01(P1 p1) {
        this.p1 = p1;
    }

    @Override
    public void run() {
        while (true){
            p1.pushService();
        }
    }
}

class C_thread01 extends Thread {

    public C1 c1;

    public C_thread01(C1 c1) {
        this.c1 = c1;
    }

    @Override
    public void run() {
        while (true){
            c1.popService();
        }
    }
}

class P1 {
    private final MyStack01 myStack01;

    public P1(MyStack01 myStack01) {
        this.myStack01 = myStack01;
    }

    public void pushService() {
        myStack01.push();
    }
}

class C1 {
    private MyStack01 myStack01;

    public C1(MyStack01 myStack01) {
        this.myStack01 = myStack01;
    }

    public void popService() {
        System.out.println("pop="+myStack01.pop());
    }
}
